// import store from '@/store'
import axios from 'axios'
import { getCookie, setCookie, debounce, isStringifyJSON } from '../utils/tool'
import { Message, Loading } from 'element-ui'
import { domain, isLoginSkip } from '../config'
import { bus } from '@/main'
import { encrypt } from '@/utils/rsaEncrypt'
import { changeOrgAuthToken } from '@/api/login'

let url = domain
// 创建一个错误
function errorCreate (msg) {
  const err = new Error(msg)
  errorLog(err)
  throw err
}

// 记录和显示错误
function errorLog (err) {
  // 打印到控制台
  if (process.env.NODE_ENV === 'development') {
    console.log(err)
  }
  // 显示提示
  if (err.response && err.response.status === 401 && location.hash !== '#/') {

    // location.href = '/#/login'
  }
  Message({
    message: err.message,
    type: 'error'
  })
}
// 创建一个 axios 实例
const request = axios.create({
  baseURL: url,
  timeout: 300000 // 请求超时时间
})
let loadingInstance = null
// 请求拦截器

request.interceptors.request.use(
  config => {
    // 在请求发送之前做一些处理
    const token = getCookie('console_login_ticket')
    // const token = 'Bearer 2VRP73SdAoJTZUwv0UsOQHQsQf3ktbmcm4eL89HHBy5eWmPTlry8CvavJib4X4JI5TiBIrTyENs59T8mLv3Uo0BHQSTxKNqAnLrLEXEOYc7hcDU1WIMit2JizsZOrysT'
    config.headers['Authorization'] = decodeURIComponent(token)
    config.headers['Access-Control-Allow-Origin'] = '*' 
    config.headers['Access-Control-Allow-Methods'] = 'POST,GET,OPTIONS,DELETE' 
    config.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type,token' 
    config.headers['token'] = decodeURIComponent(token)
    if (config.method === 'get' || config.method === 'GET') {
      config.params = config.data
    }
    if (!config.noLoadding) {
      loadingInstance = Loading.service({
        text: '请稍等',
        background: process.env.VUE_APP_VERSIONS == "dark" ? "rgba(0, 0, 0, .3)" : "rgba(225, 225, 225, .6)",
        lock: false,
        body: false
      })
      setTimeout(() => {
        loadingInstance?.close()
      }, 30000)
    }
    return config
  },
  error => {
    // 发送失败
    console.log(error)
    Promise.reject(error)
    loadingInstance.close()
  }
)
// 响应拦截器
request.interceptors.response.use(
  async response => {
    if (response.headers && response.headers.authorization) {
      // console.log(response.headers.authorization)
      setCookie('token', response.headers.authorization)
    }
    const dataAxios = response.data
    // console.log(dataAxios)
    if (loadingInstance) {
      loadingInstance.close()
    }
    if (
      dataAxios && 
      dataAxios.httpCode - 0 === 401 && 
      isLoginSkip
    ) {
      localStorage.setItem('source', encodeURIComponent(location.href))
      // if (process.env.VUE_APP_USER) {
      //   location.href = `/${process.env.VUE_APP_USER}/#/login`
      // } else {
        location.href = `/console/#/login`
      // }
      return
    }
    // 这个状态码是和后端约定的
    // const { status } = response
    
    let status = null
    if (dataAxios.status && !isNaN(dataAxios.status - 0)) {
      status = dataAxios.status
    }
    if (dataAxios.code && !isNaN(dataAxios.code - 0)) {
      status = dataAxios.code
    }
    // 根据 code 进行判断
    if (status !== null) {
      // 有 code 代表这是一个后端接口 可以进行进一步的判断
      let requestData = null
      let ignore = false

      // 判定是否拦截错误
      if (isStringifyJSON(response.config.data)) requestData = JSON.parse(response.config.data)
      if (requestData && requestData.ignore == true) {
        ignore = true
      }
      switch (status) {
        case 0:
          // [ 示例 ] code === 0 代表没有错误
          return dataAxios.result || dataAxios.result == 0 ? dataAxios.result : dataAxios
        case 200:
          // [ 示例 ] code === 0 代表没有错误
          return dataAxios.result || dataAxios.result == 0 ? dataAxios.result : dataAxios
        case 306:
          // 用户被管理员拒绝
          return
        case 307:
          // 用户还未认证信息
          return
        case 308:
          // 用户还未经过管理员审核
          return
        case 309:
          // 用户还没有机构
          return
        case 401:
            // if (isLoginSkip) {
              debounce (async function () {
                let res = await changeOrgAuthToken ({
                  grant_type: 'refresh_token',
                  client_id: 'platform',
                  client_secret: encodeURIComponent(encrypt('123456')),
                  refresh_token: getCookie('refresh_token'),
                  ignore: true
                })
                console.log(res)
                if (!res || (res && res.code && res.code == 400)) {
                  bus.$emit("isLogin", false)
                  localStorage.setItem('source', encodeURIComponent(location.href))
                  // if (process.env.VUE_APP_USER) {
                  //   location.href = `/${process.env.VUE_APP_USER}/#/login`
                  // } else {
                    location.href = `/console/#/login`
                  // }
                } else {
                  console.log(res.data)
                  let access_token = res.data.access_token
                  let refresh_token = res.data.refresh_token
                  setCookie('console_login_ticket', `Bearer ${access_token}`)
                  setCookie('console_refresh_token', refresh_token)
                  
                  location.reload()
                }
              }, 1200)()
            // } 
          return

        case 'xxx':
          // [ 示例 ] 其它和后台约定的 code
          if (!ignore) {
            errorCreate(`[ code: xxx ] ${dataAxios.message}`)
          }
          break
        default:
          if (!ignore) {
            // 不是正确的 code
            errorCreate(`${dataAxios.message}`)
          }
          break
      }
    } else {
      // 如果没有 code 代表这不是项目后端开发的接口 比如可能是 D2Admin 请求最新版本
      return dataAxios
    }
  },
  error => {
    loadingInstance.close()
    if (error && error.response) {
      switch (error.response.status) {
        case 400: error.message = `请求错误: ${error.response.data && error.response.data.msg}`; break
        case 401: error.message = '未授权，请登录'; setCookie('console_login_ticket', ''); setCookie('console_refresh_token', ''); location.href = `/#/login?source=${encodeURIComponent(location.href)}`; break
        case 403: error.message = '拒绝访问'; break
        case 404: error.message = `请求地址出错: ${error.response.config.url}`; break
        case 408: error.message = '请求超时'; break
        case 500: error.message = '服务器内部错误'; break
        case 501: error.message = '服务未实现'; break
        case 502: error.message = '网关错误'; break
        case 503: error.message = '服务不可用'; break
        case 504: error.message = '网关超时'; break
        case 505: error.message = 'HTTP版本不受支持'; break
        default: break
      }
    }
    console.log(error)
    errorLog(error)
    return Promise.reject(error)
  }
)

export default request
